//#define PROCESS_FROM_MEMORY
#define PROCESS_FROM_FILEHANDLE

/**
 * @file example_xlsxio_read.c
 * @brief XLSX I/O example illustrating how to read from an .xlsx file.
 * @author Brecht Sanders
 *
 * This example reads data from an .xslx file using the simple method.
 */

//#define PROCESS_FROM_MEMORY

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define O_BINARY 0
#ifdef PROCESS_FROM_FILEHANDLE
//#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
#include "xlsxio_read.h"
//UTF-8 version
#define X(s) s
#define XML_Char_printf printf

const char* filename = "xlsxtest.xlsx";

int main (int argc, char* argv[])
{
    filename = "xlsxtest.xlsx";

    xlsxioreader xlsxioread;

    XML_Char_printf(X("XLSX I/O library version %s\n"), xlsxioread_get_version_string());

    //open .xlsx file for reading
    int filehandle;
    if ((filehandle = open(filename, O_RDONLY | O_BINARY, 0)) == -1) {
        fprintf(stderr, "Error opening .xlsx file\n");
        return 1;
    }
    if ((xlsxioread = xlsxioread_open_filehandle(filehandle)) == NULL) {
        fprintf(stderr, "Error reading .xlsx file\n");
        return 1;
    }

    //list available sheets
    xlsxioreadersheetlist sheetlist;
    const XLSXIOCHAR* sheetname;
    // printf("Available sheets:\n");
    if ((sheetlist = xlsxioread_sheetlist_open(xlsxioread)) != NULL) {
        while ((sheetname = xlsxioread_sheetlist_next(sheetlist)) != NULL) {
            XML_Char_printf(X(" - %s\n"), sheetname);
        }
        xlsxioread_sheetlist_close(sheetlist);
    }

    //read values from first sheet
    XLSXIOCHAR* value;
    int i=0;
    // printf("Contents of first sheet:\n");
    xlsxioreadersheet sheet = xlsxioread_sheet_open(xlsxioread, NULL, XLSXIOREAD_SKIP_EMPTY_ROWS);
    while (xlsxioread_sheet_next_row(sheet)) {
        i=0;
        while ((value = xlsxioread_sheet_next_cell(sheet)) != NULL&& i<3) {
            if(i==1||i==2){
                XML_Char_printf(X("%s\t"), value);
                if(strcmp(value,"")==0){
                    xlsxioread_free(value);
                    break;
                }
            }

            xlsxioread_free(value);
            i++;
        }
        printf("\n");
    }
    xlsxioread_sheet_close(sheet);

    //clean up
    xlsxioread_close(xlsxioread);
    return 0;
}
